package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.dumain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private IStrategyCommentRepository repository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(StrategyComment comment) {

        if(!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }

        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        // 拼接条件
        Query query = new Query();

        if(qo.getDetailId() != -1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        // 查总数
        Long count = mongoTemplate.count(query, StrategyComment.class);
        if(count == 0){
            return Page.empty(); // 空分页对象
        }
        // 需要进行分页信息的设置
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);
        // 排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(sort);
        // 查询当前页的list集合
        List<StrategyComment> list = mongoTemplate.find(query, StrategyComment.class);

        // 返回分页相关信息对象
        return new PageImpl(list, pageable, count);
    }

    @Override
    public void commentThumbUp(String commentId, Long userId) {
        StrategyComment comment = repository.findById(commentId).get();
        // 1:判断是点赞还是取消点赞
        List<Long> list = comment.getThumbuplist();
        if(list.contains(userId)){
            // 3:如果是取消点赞, 点赞数-1, 将用户移除list
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            list.remove(userId);
        }else {
            // 2:如果是点赞, 点赞数+1, 将用户加入list
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            list.add(userId);
        }
        repository.save(comment);

    }


}
